const express = require('express')
const { SerialPort } = require('serialport')
const fs = require('fs')
const dayjs = require('dayjs')

const config = require('./config')
const { strToUnit8Array } = require('./hex')

const messages = require('./messages')


const app = express()

SerialPort.list().then(ports => {
    const coms = ports.map(i => i.path)
    console.log('串口列表: ==> ', coms.toString())
})

// 实例化 初始化
const instance = new SerialPort( {
    path: config.path,
    baudRate: config.baudRate,
    autoOpen: config.autoOpen,
    encoding: config.encoding,
    dataBits: config.dataBits,
}, err => {
    if(err) {
        return console.log(err.message)
    }
})

let backup = []
let backupCopy = []

instance.open(err => {
    if(err) {
        console.log('Error on open: ', err.message);
        return
    }

    console.log('port opened ' )

    let index = 0

    sendMsg(messages[0])

    setInterval(() => {
        index ++
        if (index > messages.length) {
            index = 0
        }
        const str = messages[index]
        sendMsg(str)
    }, config.INTERVAL)

})

// 收到信息
instance.on('data', data => {
    if (data && Buffer.isBuffer(data)) {
        handle(data.toString('hex'))
    }
})

/**
 * 写信息
 * @param {string} msg
 */
function sendMsg(msg) {

        // 保存日志
    saveLog().then(() => {
        instance.write(strToUnit8Array(msg), err => {
            if (err) {
                return console.log('Error on write: ', err.message)
            }

            const str = `\n 发 -> : [ ${new Date().toLocaleTimeString()} ]   ${msg} `
            console.log(str)
            backup.push(str + '\n')
        })
    })
}

/**
 * 处理数据
 * @param {string} data hex string
 */
function handle(data) {
    const str = data.toString('hex')
    let res = ''
    for (let i = 0; i < str.length; i+=2) {
       res += `${str[i]}${str[i+1]} `

    }

    const strLog = `收 -> : [ ${new Date().toLocaleTimeString()} ]   ${res} `
    backup.push(strLog  + '\n')
    console.log(strLog)

}

// 保存日志
function saveLog() {
    return new Promise((resolve, reject) => {
        if (backup.length < 1) {
            resolve()
        }

    const fileName = `${dayjs().format('YYYY-MM-DD')}.txt`
    const content = backup.toString().replaceAll(',', '')
    const path = `./logs/${fileName}`

    if (backup.length >= config.LOG_MAX) {
        fs.writeFile(path, content, {flag: 'a'}, err => {
            if (err) {
                console.log('写日志错误: ', err.toString())
                reject(err)
                return
            }
            backup = []
            resolve()
        })
    }
    })
}

app.listen(3000, () => {
    console.log('listen http://logalhost:3000');
})
